// import { reduce } from "core-js/core/array";
import $ from "jquery";

export default {
  state: {
    id: "",
    photo: "",
    username: "",
    password: "",
    token: "",
    is_login: false,
    pulling_info: true, // 是否正在拉取信息
    select_model: -1, // 0---经典匹配 1---人机对战，2--排位模式
    red_or_blue: 0, // 匹配成功之后，用户是在蓝色方还是红色方（0表示默认是蓝色方）
  },
  getters: {},
  mutations: {
    updataUser(state, user) {
      state.id = user.id;
      state.username = user.username;
      state.photo = user.photo;
      state.is_login = user.is_login;
    },

    updateUsername(state, newName) {
      state.username = newName;
    },

    updataUserPhoto(state, photo) {
      state.photo = photo;
    },

    // 更新用户在哪一方
    updateRedOrBlue(state, color) {
      state.red_or_blue = color;
    },

    // 更新用户选择的游戏模式
    updateSelectModel(state, model) {
      state.select_model = model;
    },

    updateToken(state, token) {
      state.token = token;
    },

    logout(state) {
      state.id = "";
      state.username = "";
      state.photo = "";
      state.token = "";
      state.is_login = false;
    },

    updatePullingInfo(state, pulling_info) {
      state.pulling_info = pulling_info;
    },
  },
  actions: {
    login(context, data) {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/token/",
        type: "post",
        data: {
          username: data.username,
          password: data.password,
        },
        success(resp) {
          if (resp.error_message === "success") {
            localStorage.setItem("jwt_token", resp.token);
            context.commit("updateToken", resp.token);
            data.success(resp);
          } else {
            data.error(resp);
          }
        },
        error(resp) {
          data.error(resp);
        },
      });
    },
    getinfo(context, data) {
      $.ajax({
        url: "http://127.0.0.1:3000/user/account/info/",
        type: "get",
        headers: {
          Authorization: "Bearer " + context.state.token,
        },
        success(resp) {
          if (resp.error_message === "success") {
            context.commit("updataUser", {
              ...resp,
              is_login: true,
            });
            data.success(resp);
          } else {
            data.error(resp);
          }
        },
        error(resp) {
          data.error(resp);
        },
      });
    },

    logout(context) {
      localStorage.removeItem("jwt_token");
      context.commit("logout");
    },
  },
  modules: {},
};
